import React, { useEffect, useState, useCallback, useRef } from 'react';
import { useLocation, routerRedux } from 'react-router-dom';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { FormInstance } from 'antd/lib/form';
import {
  Modal,
  Button,
  message,
  Input,
  Select,
  Upload,
  Tooltip,
  Form,
  Row,
  Col,
  Radio,
  DatePicker,
  TimePicker,
} from 'antd';
import './index.less';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import { windowUrl } from '../../../../public/global';
import { getToken, getMd5 } from '@/utils/utils';
import moment from 'moment';
// import type { UploadFile, UploadProps } from 'antd/es/upload/interface';
import update from 'immutability-helper';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import styles from './index.less'
import { getDicByKey, getOptAuthHeaders } from '@/utils/common';
import { getDictOptionsByCode } from '@/support/common';

interface DragableUploadListItemProps {
  originNode: React.ReactElement<any, string | React.JSXElementConstructor<any>>;
  file: any;
  fileList: any[];
  idx: number;
  // file: UploadFile;
  // fileList: UploadFile[];
  moveRow: (dragIndex: any, hoverIndex: any) => void;
}

const DragableUploadListItem = ({
  originNode,
  moveRow,
  file,
  idx,
  fileList,
}: DragableUploadListItemProps) => {
  const ref = useRef<HTMLDivElement>(null);
  const index = fileList.indexOf(file);
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: 'DragableUploadList',
    collect: monitor => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
      };
    },
    drop: (item: any) => {
      moveRow(item.index, index, idx);
    },
  });
  const [, drag] = useDrag({
    // type: 'DragableUploadList',
    item: {
      type: 'DragableUploadList',
      index,
    },
    collect: monitor => ({
      isDragging: monitor.isDragging(),
    }),
  });
  drop(drag(ref));
  const errorNode = <Tooltip title="Upload Error">{originNode.props.children}</Tooltip>;
  return (
    <div
      ref={ref}
      className={`ant-upload-draggable-list-item ${isOver ? dropClassName : ''}`}
      style={{ cursor: 'move' }}
    >
      {file.status === 'error' ? errorNode : originNode}
    </div>
  );
};

const displayTypeList = [
  {
    label: '无约束',
    value: 0,
  },
  {
    label: '特殊时段',
    value: 1,
  },
  {
    label: '特殊日期',
    value: 2,
  },
  {
    label: '购车纪念日',
    value: 3,
  },
  {
    label: '生日问候',
    value: 4,
  },
];

const disabledDate = (current: any) => {
  // Can not select days before today and today
  return current && current < moment().startOf('day');
};
const FormItem = Form.Item;
const { TextArea } = Input;
const { RangePicker } = DatePicker;
const uploadUrl = '/upload/single?bizType=m18';
const url = `${windowUrl}${uploadUrl}`;
let md5 = getMd5('bizType=m18');

const ContentDetailModal: React.FC = (props: any) => {
  const {
    dispatch,
    dirSid,
    modalVisible,
    contentDetails,
    contentMng: { audienceList = [] },
    closeModal,
    type,
    dicData
  } = props;

  const [form] = Form.useForm();
  const inpDisabled = type === 'view';

  const [titleMap, setTitleMap] = useState<any>({
    add: '新增内容',
    edit: '编辑内容',
    view: '内容详情',
  });
  const [tempConfig, setTempConfig] = useState<any>(
    JSON.parse(sessionStorage.getItem('tempConfig') as string) || {},
  ); //  模板配置
  const [isDisplayYear, setIsDisplayYear] = useState<boolean>(false);
  const [isDisplayDuration, setIsDisplayDuration] = useState<boolean>(false);
  const [isFormatYear, setIsFormatYear] = useState<boolean>(false);
  const [uploadFinished, setUploadFinished] = useState<boolean>(true);

  const [fileData, setFileData] = useState<any>({});

  const uploadFn = param => {
    const serverURL = `${windowUrl}/upload/single?bizType=m18`;
    const xhr = new XMLHttpRequest();
    const fd = new FormData();

    const successFn = (response: any) => {
      const obj = JSON.parse(xhr.responseText);
      if (obj.responseCode === '200') {
        const { fileRecordList } = obj || {};
        const data = fileRecordList[0];

        param.success({
          url: data.fileUri,
        });

        return false;
      }
      // 错误
      param.error({
        msg: '上传失败',
      });
    };

    const progressFn = (event: { loaded: number; total: number }) => {
      param.progress((event.loaded / event.total) * 100);
    };

    const errorFn = (response: any) => {
      param.error({
        msg: '上传失败.',
      });
    };

    xhr.upload.addEventListener('progress', progressFn, false);
    xhr.addEventListener('load', successFn, false);
    xhr.addEventListener('error', errorFn, false);
    xhr.addEventListener('abort', errorFn, false);

    fd.append('file', param.file);
    xhr.open('POST', serverURL, true);
    xhr.setRequestHeader('OptAuthorization', `${getToken()}`);
    xhr.setRequestHeader('x-dfiov-fingerprint', sessionStorage.getItem('fingerprint') || 'undefined');
    xhr.setRequestHeader('shaSign', md5);
    xhr.send(fd);
  };

  const handleEditorChange = (editorState: any, index: number) => {
    const formVal = form.getFieldsValue();
    const temps = formVal?.temps;
    temps[index].content = editorState.toHTML();
    form.setFieldsValue({
      temps,
    });
    /* const formVal = this.formRef.current?.getFieldsValue();
    const temps = formVal?.temps;
    temps[index].content = editorState.toHTML();
    this.formRef.current?.setFieldsValue({
      temps: temps,
    }); */
  };

  const moveRow = useCallback(
    (dragIndex: number, hoverIndex: number, idx: number) => {
      const tempList = fileData[`fileList${idx}`];
      const dragRow = tempList[dragIndex];
      const tempFileList = update(tempList, {
        $splice: [
          [dragIndex, 1],
          [hoverIndex, 0, dragRow],
        ],
      });
      setFileData({
        ...fileData,
        [`fileList${idx}`]: tempFileList,
      });
      const temps = form.getFieldValue('temps');
      temps[idx].content = tempFileList;
      form.setFieldsValue({
        temps,
      });
    },
    [fileData],
  );

  const renderTempForm = (data: Array<any>) => {
    const formItemLayout = {
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        md: { span: 16 },
      },
    };
    // const { tempConfig } = this.state;
    const generateTempItem = (field: any, index: number): any => {
      switch (field.type + '') {
        // 文本
        case '1': {
          const { name, key, label_name, is_require, is_mutilate, max_length } = field;
          const placeholder = `请输入${label_name || ''}`;
          return (
            <Col span={24} key={index}>
              <FormItem
                {...formItemLayout}
                key={index}
                name={[name, 'content']}
                label={label_name}
                rules={[{ required: is_require === 1, message: `请输入${label_name || ''}` }]}
              >
                {is_mutilate === 1 ? (
                  <TextArea
                    rows={4}
                    disabled={inpDisabled}
                    placeholder={placeholder}
                    autoComplete="off"
                    allowClear
                    showCount
                    maxLength={max_length}
                  />
                ) : (
                  <Input
                    disabled={inpDisabled}
                    placeholder={placeholder}
                    autoComplete="off"
                    allowClear
                    maxLength={max_length}
                  />
                )}
              </FormItem>
            </Col>
          );
        }
        // 富文本
        case '2': {
          const { name, key, label_name, is_require } = field;
          const editorProps = {
            media: {
              allowPasteImage: false,
              image: true,
              video: true,
              audio: false,
              uploadFn: uploadFn,
            },
            // value: this.state[`editorState${index}`],
            value: '',
            readOnly: inpDisabled,
          };
          /* const tempValue =
            (this.state.contentDetailData &&
              JSON.parse(this.state.contentDetailData?.contentJson)) ||
            []; */
          const tempValue = (contentDetails && JSON.parse(contentDetails?.contentJson)) || [];
          const defaultValue = tempValue[index]?.content || '';
          return (
            <Col span={24} key={index}>
              <FormItem
                {...formItemLayout}
                name={[name, 'content']}
                label={label_name}
                rules={
                  is_require === 1
                    ? [
                        {
                          required: true,
                          validator: (_, value, callback) => {
                            // if (value.isEmpty()) {
                            // isEmpty校验会报错
                            if (!value || value === '<p></p>') {
                              callback('请填写正文内容');
                            } else {
                              callback();
                            }
                          },
                        },
                      ]
                    : []
                }
                key={index}
              >
                <BraftEditor
                  placeholder="请输入正文内容"
                  defaultValue={BraftEditor.createEditorState(defaultValue)}
                  contentStyle={{ minHeight: 220, boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)' }}
                  onChange={val => handleEditorChange(val, index)}
                  {...editorProps}
                />
              </FormItem>
            </Col>
          );
        }
        // 图片
        case '3': {
          const {
            name,
            key,
            label_name,
            is_require,
            image_format,
            image_length,
            image_width,
            graphics,
            image_size = Infinity,
          } = field;
          const imgList =
            data[index]?.content?.map((url: string, imgIndex: number) => {
              return {
                uid: imgIndex,
                name: '',
                status: 'done',
                url,
              };
            }) || [];
          const uploadButton = (
            <div>
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>上传照片</div>
            </div>
          );
          const beforeUpload = (file: any) => {
            const currentFileType = file.name.substring(file.name.lastIndexOf('.')); //解析文件名后缀
            const isJpgOrPng = image_format
              ? image_format.split(';').indexOf(currentFileType) > -1
              : true;
            if (!isJpgOrPng) {
              message.error('请上传规定格式图片');
            }
            const isLt2M = image_size ? file.size / 1024 / 1024 < image_size : true;
            if (!isLt2M) {
              message.error(`图片大小不超过${image_size}Mb`);
            }
            return isJpgOrPng && isLt2M;
          };
          const handleChange = (info: any) => {
            let { fileList, file } = info;
            setUploadFinished(false);
            if (file.status === 'done' && file.response && file.response.responseCode === '200') {
              setUploadFinished(true);
              message.success(`${file.name} 上传成功`);
            } else if (
              file.status === 'done' &&
              file.response &&
              file.response.responseCode !== '200'
            ) {
              setUploadFinished(true);
              message.error(file.response.responseMsg);
              // this.setState({ fileList: [] });
              fileList = fileList.slice(0, -1);
              // return;
            } else if (file.status === 'removed') {
              setUploadFinished(true);
              message.success('删除成功');
            } else if (file.status === 'error') {
              message.error(`${file.name} 上传失败`);
              setUploadFinished(true);
              fileList = fileList.slice(0, -1);
              // return;
            } else if (!file.status) {
              setUploadFinished(true);
              fileList = fileList.slice(0, -1);
              message.error(`${file.name} 上传失败`);
              // return;
            }
            const temps = form.getFieldValue('temps');
            temps[index].content = fileList.map(
              (item: { response: any; uid: any; status: any; name: any; url: any }) => {
                return {
                  uid: item.uid,
                  status: item.status,
                  name: item.name,
                  // url: item.response?.fileRecordList[0]?.fileUri,
                  url: item.response ? item.response.fileRecordList[0]?.fileUri : item.url,
                };
              },
            );
            form.setFieldsValue({
              temps,
            });
            setFileData({
              ...fileData,
              [`fileList${index}`]: temps[index].content,
              // [`fileList${index}`]: fileList,
            });
          };
          // const temps = form.getFieldValue('temps');
          // const fileList: any[] = temps[index].content || [];
          // const fileList = this.state[`fileList${index}`] || [];
          const fileList = fileData[`fileList${index}`] || [];
          return (
            <>
              <Col span={24} key={index}>
                <FormItem
                  {...formItemLayout}
                  name={[name, 'content']}
                  label={label_name}
                  rules={[{ required: is_require === 1, message: `请上传图片` }]}
                  key={index}
                >
                  {/* <DndContext sensors={[sensor]} onDragEnd={(event: DragEndEvent) => {
                    onDragEnd(event, index, l);
                  }}>
                    <SortableContext items={fileList.map(i => {
                      return i.uid;
                    })} strategy={verticalListSortingStrategy}>
                      <Upload 
                        action={url} 
                        disabled={inpDisabled} 
                        listType="picture-card" 
                        multiple={false} 
                        fileList={fileList} 
                        headers={{
                          OptAuthorization: `${getToken()}`,
                          shaSign: md5
                        }} 
                        beforeUpload={beforeUpload} 
                        onChange={handleChange} 
                        itemRender={(originNode, file) => 
                          <DraggableUploadListItem 
                            originNode={originNode} 
                            file={file} />
                        }>
                        {fileList.length && graphics && fileList.length >= graphics ? null : uploadButton}
                      </Upload>
                    </SortableContext>
                  </DndContext> */}

                  <DndProvider backend={HTML5Backend}>
                    <Upload
                      action={url}
                      disabled={inpDisabled}
                      listType="picture-card"
                      multiple={false}
                      fileList={[...fileList]}
                      headers={{
                        OptAuthorization: `${getToken()}`,
                        ...getOptAuthHeaders(),
                        shaSign: md5,
                      }}
                      beforeUpload={beforeUpload}
                      onChange={handleChange}
                      itemRender={(originNode, file, currFileList) => (
                        <DragableUploadListItem
                          originNode={originNode}
                          file={file}
                          fileList={currFileList}
                          idx={index}
                          moveRow={(dragIndex: any, hoverIndex: any) => {
                            moveRow(dragIndex, hoverIndex, index);
                          }}
                        />
                      )}
                    >
                      {fileList.length && graphics && fileList.length >= graphics
                        ? null
                        : uploadButton}
                    </Upload>
                  </DndProvider>
                  {/* <Upload
                    listType="picture-card"
                    multiple={false}
                    headers={{
                      OptAuthorization: `${getToken()}`,
                      shaSign: md5,
                    }}
                    fileList={[...fileList]}
                    // fileList={[]}
                    action={url}
                    beforeUpload={beforeUpload}
                    onChange={e => handleChange(e, index)}
                  >
                    {fileList.length && graphics && fileList.length >= graphics
                      ? null
                      : uploadButton}
                  </Upload> */}
                </FormItem>
              </Col>
              <Col span={24}>
                <span>
                  {image_format && '只支持' + image_format + ' 格式，'}
                  {image_length &&
                    image_width &&
                    '尺寸大小为：' + image_length + '*' + image_width + '，'}
                  {graphics && '最多上传' + graphics + ' 张图片'}
                </span>
              </Col>
            </>
          );
        }
        // 文件
        case '4': {
          const { name, key, label_name, is_require, file_format, file_size = Infinity } = field;
          const beforeUpload = (file: any) => {
            const currentFileType = file.name.substring(file.name.lastIndexOf('.')); //解析文件名后缀
            const isFormatMatch = file_format
              ? file_format.split(';').indexOf(currentFileType) > -1
              : true;
            if (!isFormatMatch) {
              message.error('请上传规定格式文件');
            }
            const isLt2M = file_size ? file.size / 1024 / 1024 < file_size : true;
            if (!isLt2M) {
              message.error(`文件大小不超过${file_size}Mb`);
            }
            return isFormatMatch && isLt2M;
          };
          const handleChange = (info: any) => {
            let { fileList, file } = info;
            setUploadFinished(false);
            if (file.status === 'done' && file.response && file.response.responseCode === '200') {
              setUploadFinished(true);
              message.success(`${file.name} 上传成功`);
            } else if (
              file.status === 'done' &&
              file.response &&
              file.response.responseCode !== '200'
            ) {
              setUploadFinished(true);
              message.error(file.response.responseMsg);
              fileList = fileList.slice(0, -1);
              // return;
            } else if (file.status === 'removed') {
              setUploadFinished(true);
              message.success('删除成功');
            } else if (file.status === 'error') {
              message.error(`${file.name} 上传失败`);
              setUploadFinished(true);
              fileList = fileList.slice(0, -1);
              // return;
            } else if (!file.status) {
              setUploadFinished(true);
              fileList = fileList.slice(0, -1);
              message.error(`${file.name} 上传失败`);
              // return;
            }

            const temps = form.getFieldValue('temps');
            temps[index].content = fileList.map(
              (item: { response: any; uid: any; status: any; name: any; url: any }) => {
                return {
                  uid: item.uid,
                  status: item.status,
                  name: item.name,
                  url: item.response ? item.response.fileRecordList[0]?.fileUri : item.url,
                };
              },
            );
            form.setFieldsValue({
              temps,
            });
            setFileData({
              ...fileData,
              [`fileList${index}`]: fileList,
            });
          };
          // const fileList = this.state[`fileList${index}`] || [];
          // const temps = form.getFieldValue('temps');
          // const fileList: any[] = temps[index].content || [];
          const fileList = fileData[`fileList${index}`] || [];

          const beforePreviewUpload = (file) => {
            const currentFileType = file.name.substring(
              file.name.lastIndexOf(".")
            ); //解析文件名后缀

            const accepts = [".png", ".jpg", ".jpeg"];
            if (!accepts.includes(currentFileType)) {
              message.error(`封面只支持${accepts.join("、")}格式图片`);
              return false;
            }
            return true;
          };

          const handlePreviewChange = ({ info, index, file, fileList }) => {
            const pictureInfo = info.file;
            if (!["done", "error"].includes(pictureInfo.status)) {
              return;
            }
            file.previewUrl = pictureInfo.response ? pictureInfo.response.fileRecordList[0]?.fileUri : pictureInfo.url;
            file.thumbnailUrl = pictureInfo.response ? pictureInfo.response.fileRecordList[0]?.fileUri: pictureInfo.fileUri;
            const _files = fileList.map(
              (item: { response: any; uid: any; status: any; name: any; url: any }) => {
                return {
                  uid: item.uid,
                  name: item.name,
                  url: item.response ? item.response.fileRecordList[0]?.fileUri : item.url,
                  previewUrl: item.previewUrl,
                  thumbnailUrl: item.thumbnailUrl
                };
              },
            );

            const temps = form.getFieldValue('temps');
            temps[index].content = _files;
            form.setFieldsValue({
              temps,
            });
            setFileData({
              ...fileData,
              [`fileList${index}`]: _files,
            });
          }

          const handleDeleteFile = (file, fileList, index) => {
            const _files = fileList.map((item) => {
              if (item.uid === file.uid) {
                delete file.previewUrl;
                delete field.thumbnailUrl;
                return file;
              }
              return item;
            });
            
            const temps = form.getFieldValue('temps');
            temps[index].content = _files;
            form.setFieldsValue({
              temps,
            });
            setFileData({
              ...fileData,
              [`fileList${index}`]: _files,
            });
          }
          
          const contentVideoAccepts = getDictOptionsByCode(dicData, 'contentVideoAccepts').reduce((target, last) => {
            return [
              ...target,
              last.label
            ]
          }, []) as any as string[];
          return (
            <>
              <Col span={24} key={index}>
                <FormItem
                  {...formItemLayout}
                  name={[name, 'content']}
                  label={label_name}
                  rules={[{ required: is_require === 1, message: `请上传` }]}
                  key={index}
                >
                  <Upload
                    disabled={inpDisabled}
                    multiple={false}
                    fileList={fileList}
                    action={url}
                    headers={{
                      OptAuthorization: `${getToken()}`,
                      ...getOptAuthHeaders(),
                      shaSign: md5,
                    }}
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                    itemRender={ (originNode, file) => {
                      let fileUrl =  (file.name|| file.response?.fileRecordList[0]?.fileUri)
                      return (
                        <div>
                          {originNode}
                          {
                            fileUrl &&
                            contentVideoAccepts.includes(
                              fileUrl.slice(fileUrl.lastIndexOf("."))
                            ) && (
                          <div className={styles["file-item"]}>
                            <div className="file-box">
                              <div className="file-opt">
                                { (
                                    <Upload
                                      accept=".png,.jpg,.jpeg"
                                      multiple={false}
                                      showUploadList={false}
                                      headers={{
                                        OptAuthorization: `${getToken()}`,
                                        ...getOptAuthHeaders(),
                                        shaSign: md5,
                                      }}
                                      action={url}
                                      beforeUpload={beforePreviewUpload}
                                      onChange={(info) =>
                                        handlePreviewChange({
                                          info,
                                          index,
                                          file,
                                          fileList,
                                        })
                                      }
                                    >
                                      <span className="file-preview">上传封面</span>
                                    </Upload>
                                  )}
                                <div
                                  className="file-delete"
                                  onClick={() =>
                                    handleDeleteFile(file, fileList, index)
                                  }
                                >
                                  删除
                                </div>
                              </div>
                            </div>
                            {file.previewUrl && (
                              <div className="file-box preview-box">
                                <img
                                  className="preview-img"
                                  src={file.previewUrl}
                                  onClick={() => {
                                    window.open(file.previewUrl, "_blank");
                                  }}
                                />
                              </div>
                            )}
                          </div>
                          )
                        }
                        </div>
                      )
                    } }
                  >
                    <Button icon={<UploadOutlined />}>上传文件</Button>
                  </Upload>
                </FormItem>
              </Col>
              <Col span={24}>
                <span>{file_format && '只支持' + file_format + ' 格式'}</span>
              </Col>
            </>
          );
        }
      }
    };
    return (
      <Form.List name="temps">
        {fields => (
          <>
            {fields.map(({ key, name }, index) => {
              return generateTempItem({ key, name, ...tempConfig[index] }, index);
            })}
          </>
        )}
      </Form.List>
    );
  };

  const close = () => {
    closeModal();
    form.resetFields();
  };

  const handleSubmit = () => {
    form.submit();
  };

  const finish = (vals: any) => {
    const url = contentDetails ? 'contentMng/editTempContent' : 'contentMng/addTempContent';
    const format = vals.displayType == 1 ? 'HH:mm' : 'YYYY-MM-DD';
    const params = {
      ...contentDetails,
      contentItemSid: sessionStorage.getItem('contentId'),
      templateSid: sessionStorage.getItem('tempId'),
      ...vals,
      audienceName: audienceList.find((item: { sid: any }) => item.sid === vals.audienceSid)
        ?.objectGroupName,
      contentJson: JSON.stringify(vals.temps),
      displayStart: vals.range && vals.range[0].format(format),
      displayEnd: vals.range && vals.range[1].format(format),
      displayType: vals.displayType || 0,
    };
    if (dirSid) params['dirSid'] = dirSid;
    dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          close();
          message.success(`${contentDetails ? '编辑成功' : '新增成功'}`);
        }
      },
    });
  };

  const onDisplayTypeChange = (displayType: number) => {
    // 特定日期
    // eslint-disable-next-line eqeqeq
    setIsDisplayYear(displayType == 2);
    // eslint-disable-next-line eqeqeq
    setIsDisplayDuration(displayType == 2 || displayType == 1);
    form.resetFields(['range']);
  };

  useEffect(() => {
    dispatch({
      type: 'contentMng/queryAudienceList',
      payload: {},
    });
    if (contentDetails) {
      const detailData = JSON.parse(contentDetails?.contentJson);
      const format = contentDetails.displayType == 1 ? 'HH:mm' : 'YYYY-MM-DD';
      let range = [
        contentDetails.displayStart && moment(contentDetails.displayStart, format),
        contentDetails.displayEnd && moment(contentDetails.displayEnd, format),
      ];
      form?.setFieldsValue({
        ...contentDetails,
        range,
        temps: detailData,
      });
      setIsDisplayYear(contentDetails.displayType == 2);
      setIsDisplayDuration(contentDetails.displayType == 2 || contentDetails.displayType == 1);
      setIsFormatYear(contentDetails.displayYear == 1);
      const tempFileData = {};
      detailData.forEach((item: { type: string; content: any }, index: any) => {
        if (item.type == '3' || item.type == '4') {
          tempFileData[`fileList${index}`] = item.content || [];
          /* setFileData({
            ...fileData,
            [`fileList${index}`]: item.content || [],
          }) */
        }
        /* if (item.type == '2') {
          this.setState({
            [`editorState${index}`]: BraftEditor.createEditorState(item.content || ''),
          });
        } */
      });
      setFileData(tempFileData);
    }
  }, []);

  const audienceOptions = audienceList.map((audience: { sid: any; objectGroupName: any }) => (
    <Select.Option key={audience.sid} value={audience.sid}>
      {audience.objectGroupName}
    </Select.Option>
  ));
  const displayTypeOptions = displayTypeList.map((item: { value: number; label: string }) => (
    <Select.Option key={item.value} value={item.value}>
      {item.label}
    </Select.Option>
  ));
  const footer = (
    <div>
      {type === 'view' ? (
        <>
          <Button size="small" onClick={close}>
            返回
          </Button>
        </>
      ) : (
        <>
          <Button size="small" onClick={close}>
            取消
          </Button>
          <Button
            size="small"
            // loading={loading}
            onClick={handleSubmit}
            type="primary"
            loading={!uploadFinished}
          >
            保存
          </Button>
        </>
      )}
    </div>
  );

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 12 },
      md: { span: 16 },
    },
  };

  return (
    <Modal
      width={'60vw'}
      footer={footer}
      title={titleMap[type]}
      visible={modalVisible}
      onCancel={close}
    >
      <Form
        form={form}
        style={{
          marginTop: 12,
        }}
        initialValues={{
          temps: tempConfig,
          displayType: 0,
        }}
        onFinish={finish}
      >
        <Row gutter={24}>
          <Col span={8}>
            <FormItem
              {...formItemLayout}
              label="内容名称"
              name="contentName"
              rules={[{ required: true, message: '请输入内容名称' }]}
            >
              <Input
                maxLength={200}
                disabled={inpDisabled}
                placeholder="请输入内容名称"
                allowClear
              />
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem {...formItemLayout} label="受众对象" name="audienceSid">
              <Select showSearch={false} disabled={inpDisabled} allowClear placeholder="请选择">
                {audienceOptions}
              </Select>
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem {...formItemLayout} label="跳转代码" name="referenceCode" rules={[]}>
              <Input
                maxLength={500}
                disabled={inpDisabled}
                allowClear
                placeholder="请输入跳转代码"
              />
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem {...formItemLayout} label="展现时机" name="displayType">
              <Select
                disabled={inpDisabled}
                showSearch={false}
                allowClear={false}
                onChange={onDisplayTypeChange}
                placeholder="请选择"
                // defaultValue={0}
              >
                {displayTypeOptions}
              </Select>
            </FormItem>
          </Col>
          {isDisplayYear && (
            <Col span={8}>
              <FormItem {...formItemLayout} label="精确到年" name="displayYear" initialValue={0}>
                <Radio.Group
                  disabled={inpDisabled}
                  onChange={e => {
                    form?.resetFields(['range']);
                    setIsFormatYear(e.target.value == 1);
                  }}
                  /* onChange={e => {
                      this.setState(
                        {
                          isFormatYear: e.target.value == 1,
                        },
                        () => {
                          this.formRef.current?.resetFields(['range']);
                        },
                      );
                    }} */
                >
                  <Radio value={0}>否</Radio>
                  <Radio value={1}>是</Radio>
                </Radio.Group>
              </FormItem>
            </Col>
          )}
          {isDisplayDuration && (
            <Col span={8}>
              <FormItem
                wrapperCol={{ span: 24 }}
                name="range"
                rules={[{ required: isDisplayDuration, message: '请选择' }]}
              >
                {isDisplayYear ? (
                  <RangePicker
                    format={isFormatYear ? 'YYYY-MM-DD' : 'MM-DD'}
                    disabled={inpDisabled}
                    disabledDate={isFormatYear && disabledDate}
                  />
                ) : (
                  <TimePicker.RangePicker disabled={inpDisabled} format={'HH:mm'} />
                )}
              </FormItem>
            </Col>
          )}
          <Col span={8}>
            <FormItem {...formItemLayout} label={'内容版本号'} name="contentVersion" rules={[]}>
              <Input
                maxLength={100}
                disabled={inpDisabled}
                allowClear
                placeholder={'请输入内容版本号'}
              />
            </FormItem>
          </Col>
        </Row>
        <Row>{renderTempForm(tempConfig)}</Row>
      </Form>
    </Modal>
  );
};
export default connect(({ vehicleInfoQuery, contentMng }) => ({
  vehicleInfoQuery,
  contentMng,
}))(ContentDetailModal);
